package com.digitalchina.lxnsy.activity.mainConsult;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONObject;
import com.apkfuns.logutils.LogUtils;
import com.baoyz.actionsheet.ActionSheet;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.ExpertsDetailActivity;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.entity.MainCosultVO;
import com.digitalchina.lxnsy.entity.MessageVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.TimeUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.ConsultDetailHolder;
import com.digitalchina.lxnsy.xml.UserXML;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


public class ConsultDetailActivity extends BaseActivity {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.iv_img)
    ImageView ivImg;
    @Bind(R.id.iv_evaluate)
    ImageView ivEvaluate;
    @Bind(R.id.et_msg)
    EditText etMsg;
    @Bind(R.id.tv_send)
    TextView tvSend;
    @Bind(R.id.layout_bottom)
    RelativeLayout layoutBottom;
    @Bind(R.id.layout_bottom2)
    RelativeLayout layoutBottom2;
    @Bind(R.id.tv_status)
    TextView tvStatus;
    @Bind(R.id.tv_tips)
    TextView tvTips;


    TextView tvName;
    TextView tvTitle;
    TextView tvArea;
    TextView tvTime;
    LinearLayout layoutExpert;

    String tel = "";
    String workTime = "";



    private RecyclerArrayAdapter adapter;
    private View headView;//头布局
    private MainCosultVO vo;

    private List<MessageVO> msgList = new ArrayList<>();
    private MessageVO msg = new MessageVO();

    // 图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_consult_detail);
        setTitle("咨询详情");
        setRightText("售后");
    }

    @Override
    public void initMember() {


        vo = (MainCosultVO) getIntent().getSerializableExtra("vo");

        //会话状态 0-未提问 1-专家已回复 2-待回复 3-待评价 4-已评价 5-已失效
        switch (vo.getSessionStatus()) {
            case "0":
                break;
            case "1":
                break;
            case "2":
                break;
            case "3":
                layoutBottom.setVisibility(View.GONE);
                layoutBottom2.setVisibility(View.VISIBLE);
                tvStatus.setText("待评价");
                break;
            case "4":
                layoutBottom.setVisibility(View.GONE);
                layoutBottom2.setVisibility(View.VISIBLE);
                tvStatus.setText("已评价");
                break;
            case "5":
                layoutBottom.setVisibility(View.GONE);
                layoutBottom2.setVisibility(View.VISIBLE);
                tvStatus.setText("已失效");
                break;
        }


        getSessionDetails();

        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）

        headView = LayoutInflater.from(activity).inflate(R.layout.view_consult_detail, null);
        tvName = headView.findViewById(R.id.tv_name);
        tvTitle = headView.findViewById(R.id.tv_title);
        tvArea = headView.findViewById(R.id.tv_area);
        tvTime = headView.findViewById(R.id.tv_time);
        layoutExpert = headView.findViewById(R.id.layout_expert);

//        tvName.setText(vo.getName());
//        tvTitle.setText(vo.getTitle());
//        tvTips.setText(vo.getSessionLoseValidTime() + "后过期");
//        tvTime.setText(vo.getSessionStartTime());

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));
        recyclerView.setAdapter(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ConsultDetailHolder(parent, vo);
            }
        });

        //如果是专家则显示评价按钮 和 隐藏顶部信息
        if (Constant.USER_TYPE_EXPERT.equals(UserXML.getUserType(activity))) {
            ivEvaluate.setVisibility(View.VISIBLE);
        } else {
            adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
                @Override
                public View onCreateView(ViewGroup parent) {

                    return headView;
                }

                @Override
                public void onBindView(View headerView) {


                }
            });
        }

    }

    @Override
    public void addListener() {

        //已评价未评价
        layoutBottom2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ( UserXML.getUserId(activity).equals(vo.getExpertUserId()) ||vo.getIsEvaluate() == 1) {
                    GotoUtil.gotoActivity(activity, ConsultEvaluateDetailActivity.class, "consultSessionId", vo.getId());
                } else if (vo.getIsEvaluate() == 0) {
                    GotoUtil.gotoForResultActivity(activity, ConsultEvaluateAddActivity.class, 90, "consultSessionId", vo.getId());
                }
            }
        });

        //专家详情
        layoutExpert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GotoUtil.gotoActivity(activity, ExpertsDetailActivity.class, "id", vo.getExpertId());
            }
        });


        //发送文本
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1-纯文本消息 2-图片消息 3-语音消息 4-评价
                if (StringUtil.isStrEmpty(etMsg.getText().toString())) {
                    showToast("请输入内容");
                } else {
                    addMessageInfo(1, etMsg.getText().toString(), mHandler);
                }

            }
        });


        //发送图片
        ivImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(activity, ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT);
            }
        });

        //发起评价
        ivEvaluate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1-纯文本消息 2-图片消息 3-语音消息 4-评价
                addMessageInfo(4, "专家发起评价", mHandler);
            }
        });


    }


    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_S_0: // 详情
                        callBack(message.obj);
                        break;
                    case MSG_F_0:
                        showToast(message.obj.toString());
                        break;
                    case MSG.MSG_ADD_MESSAGE_INFO_SUCCESS: // 发送消息成功
                        adapter.add(msg);
                        recyclerView.smoothScrollToPosition(adapter.getCount());

                        break;
                    case MSG.MSG_ADD_MESSAGE_INFO_FIELD:
                        showToast(message.obj.toString());
                        break;
                    case MSG.MSG_FILE_UPLOAD_SUCCESS: // 上传图片
                        dismissDialog();
                        FileVO fileVO = FastJsonUtil.getBean(message.obj.toString(), "body", "fileStorage", FileVO.class);
                        //1-纯文本消息 2-图片消息 3-语音消息 4-评价
                        addMessageInfo(2, fileVO.getName(), mHandler);
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(message.obj.toString() + "");
                        break;
                    case MSG_S_4: //融云过来的数据
                        MessageVO msgVO = FastJsonUtil.getBean(message.obj.toString(), "", "msg", MessageVO.class);
                        LogUtils.e(msgVO);
                        if (activity != null && !activity.isFinishing() && adapter != null && adapter.getCount() >= 0) {
                            if (msgVO != null && msgVO.getConsultSessionId() != null && msgVO.getConsultSessionId().equals(vo.getId())) {
                                adapter.add(msgVO);
                                recyclerView.smoothScrollToPosition(adapter.getCount());
                            }
                        }

                        break;
                }
                return false;
            }
        });
    }


    @Override
    public void callBack(Object object) {
        ConsultListVO consultListVO = FastJsonUtil.getBean(object.toString(), "", ConsultListVO.class);
        if (consultListVO != null) {

            msgList = consultListVO.getMessageList();
            tvArea.setText(consultListVO.getAreaType());
            tvName.setText(consultListVO.getExpertName());
            tvTitle.setText(consultListVO.getExpertTitle());

            tel = consultListVO.getKeFuTel();
            workTime = consultListVO.getWorkTime();

            if("1".equals(vo.getIsFee())){
                tvTips.setText(vo.getSessionLoseValidTime() + "或" + consultListVO.getSendNum() + "次回复后问题关闭");
            }else{
                tvTips.setText(vo.getSessionLoseValidTime() + "后问题关闭");
            }


            adapter.addAll(msgList);
        }

    }

    @Override
    public void rightOnClick() {
        ActionSheet.createBuilder(this, getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("客服热线", "申请退款")
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                        switch (index) {
                            case 0:
                                new MaterialDialog.Builder(activity)
                                        .title("客服热线")
                                        .content("客服电话：" + tel + "\n工作时间：" + workTime)
                                        .positiveText("拨打电话")
                                        .negativeText("取消")
                                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                                            @Override
                                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                Utils.callPhone(activity, tel);
                                            }
                                        })
                                        .show();
                                break;
                            case 1:
                                if (StringUtil.isStrEmpty(vo.getConsultRefundApplyId())) {
                                    GotoUtil.gotoForResultActivity(activity, ApplyRefundActivity.class, 88, "consultSessionId", vo.getId());
                                } else {
                                    GotoUtil.gotoActivity(activity, ApplyRefundDetailActivity.class, "consultRefundApplyId", vo.getConsultRefundApplyId());
                                }
                                break;
                        }
                    }
                }).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    //回话详情列表
    public void getSessionDetails() {
        HttpParams params = new HttpParams();
        params.put("consultSessionId", vo.getId());

        OkHttpUtil.post(activity, URL.URL_GET_SESSION_DETAILS, "", params, mHandler,
                MSG_S_0, MSG_F_0);
    }

    /**
     * 1-纯文本消息 2-图片消息 3-语音消息 4-评价
     *
     * @param msgType
     * @param handler
     */
    public void addMessageInfo(int msgType, String content, Handler handler) {
        etMsg.setText("");
        HttpParams params = new HttpParams();
        params.put("sendUser", UserXML.getUserId(activity));
        String toUser;
        if (UserXML.getUserId(activity).equals(vo.getExpertUserId())) {
            toUser = vo.getSessionStartUserId();
        } else {
            toUser = vo.getExpertUserId();
        }
        params.put("toUser", toUser);
        params.put("content", content);
        params.put("msgType", String.valueOf(msgType));
        params.put("consultSessionId", vo.getId());


        //本地展示msg
        msg.setMsgType(msgType);
        msg.setContent(content);
        msg.setSendUser(UserXML.getUserId(activity));

        msg.setCreateTime(TimeUtil.getCurrentTime());
        msg.setSendUserImg(UserXML.getImagePath(activity));
        msg.setToUser(toUser);
        msg.setConsultSessionId(vo.getId());

        OkHttpUtil.post(activity, URL.URL_ADD_MESSAGE_INFO, "", params, handler,
                MSG.MSG_ADD_MESSAGE_INFO_SUCCESS, MSG.MSG_ADD_MESSAGE_INFO_FIELD);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    showDialog("正在上传图片...");
                    BusinessFile.imageCompressAndUpload(this, images.get(0).path, mHandler);
                }
            }
        } else if (resultCode == RESULT_OK) {
            if (requestCode == 88) {
                String id = (String) data.getSerializableExtra("consultRefundApplyId");
                vo.setConsultRefundApplyId(id);
            } else if (requestCode == 89) {
                vo.setIsEvaluate(1);
                adapter.notifyDataSetChanged();
            } else if (requestCode == 90) {
                vo.setIsEvaluate(1);
                tvStatus.setText("已评价");
                adapter.notifyDataSetChanged();
            }
        }
    }
}
